package edu.sctu.yueding.fragment;

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.TypeReference;
import com.android.volley.Response;
import com.android.volley.VolleyError;

import java.util.ArrayList;
import java.util.List;

import edu.sctu.yueding.R;
import edu.sctu.yueding.adapter.IndexListViewAdapter;
import edu.sctu.yueding.adapter.IndexVoteAdapter;
import edu.sctu.yueding.adapter.ViewPagerAdapter;
import edu.sctu.yueding.bean.HomeHeadBean;
import edu.sctu.yueding.bean.HomeListViewBean;
import edu.sctu.yueding.bean.JsonBaseListBean;
import edu.sctu.yueding.bean.MetaBean;
import edu.sctu.yueding.bean.VoteBean;
import edu.sctu.yueding.config.CacheConfig;
import edu.sctu.yueding.config.URLConfig;
import edu.sctu.yueding.utils.DateUtils;
import edu.sctu.yueding.utils.L;
import edu.sctu.yueding.utils.UpdateManager;
import edu.sctu.yueding.utils.httputils.GetVolleyHttp;
import edu.sctu.yueding.utils.httputils.SharePreference;
import edu.sctu.yueding.view.XListView;


/**
 * Created by Administrator on 2016/8/1.
 */
public class IndexFragment extends Fragment implements XListView.IXListViewListener {

    private View headView;
    private View voteView;
    private ViewPager viewPager;
    private XListView listView;
    private ListView voteListView;
    private List<ImageView> cursorList;
    private ImageView imageView;
    private List<View> views;
    private TextView theme;
    private ImageView viewpagerImage;
    private TextView address;
    private TextView phoneNumber;
    private TextView joinNumber;
    private Activity mActivity;
    private RelativeLayout mProgressBarRel;
    private int page = 0;
    private JsonBaseListBean<HomeListViewBean> newsData = null;
    private IndexListViewAdapter newsAdapter;
    private boolean isAddAll = true;
    private View view = null;
    private JsonBaseListBean<HomeHeadBean> homeHeadBean = null;
    private JsonBaseListBean<VoteBean> voteBean = null;
    private ViewPagerAdapter bannerAdapter = null;
    private IndexVoteAdapter voteAdapter = null;
    private boolean isInit = false;


    // 要申请的权限
    private String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS};


    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.index_fragment, container, false);
            mActivity = getActivity();
            mProgressBarRel = (RelativeLayout) view.findViewById(R.id.id_index_fragment_progress_bar);
            headView = LayoutInflater.from(mActivity).inflate(R.layout.index_fragment_listview_head, null);
            listView = (XListView) view.findViewById(R.id.index_fragment_listView);
            voteView = LayoutInflater.from(mActivity).inflate(R.layout.index_fragment_vote_listview, null);
            voteListView = (ListView) voteView.findViewById(R.id.index_fragment_vote_listView);
            viewPager = (ViewPager) headView.findViewById(R.id.index_fragment_viewpager);
            if (!isInit) {
                listView.addHeaderView(headView);
                listView.addHeaderView(voteView);
//                initData();
//                initListView();
            } else {
                mProgressBarRel.setVisibility(View.GONE);
            }
        }
        isNewest();
        listView.setPullLoadEnable(true);
        listView.setPullRefreshEnable(true);
        listView.setXListViewListener(this);

        return view;
    }

    private void initData() {

        /**
         * banner
         */
        GetVolleyHttp.getInstance(mActivity).getStringGETJsonData(URLConfig.URL_HOME_HEAD,
                listener, errorListener, "");

        /**
         * 投票
         */
        GetVolleyHttp.getInstance(mActivity).getStringGETJsonData(URLConfig.URL_HOME_VOTE,
                voteListener, errorListener, "");

    }

    @Override
    public void onResume() {
        super.onResume();
        if (isInit) {
            setBannerAdapter();
            setVoteAdapter();
        } else if (homeHeadBean == null || voteBean == null || newsData == null) {
            initData();
            initListView();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        isInit = false;
    }

    @Override
    public void onStop() {
        super.onStop();
        isInit = false;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        isInit = false;
    }

    /**
     * 错误  回调
     */
    Response.ErrorListener errorListener = new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            L.d("", "");
        }
    };

    private void setBannerAdapter() {
        if (bannerAdapter == null) {
            bannerAdapter = new ViewPagerAdapter(views, mActivity, homeHeadBean.getData());
        }
        viewPager.setAdapter(bannerAdapter);
        if (views != null && !isInit) {
            setCursor(views);
        }

        viewPager.setOnPageChangeListener(new MyOnPageChangeListener());
    }

    private void setVoteAdapter() {
        if (voteBean != null) {
            if (voteBean.getData() != null) {
                if (voteBean.getData().size() > 0) {
                    if (voteAdapter == null) {
                        voteAdapter = new IndexVoteAdapter(mActivity, voteBean.getData());
                    }
                    voteListView.setAdapter(voteAdapter);
                    setListViewHeightBasedOnChildren(voteListView);
                } else {

                }
            } else {
                initData();
                initListView();
                setVoteAdapter();
            }
        }

    }

    /**
     * banner 成功 回调
     */
    Response.Listener<String> listener = new Response.Listener<String>() {
        @Override
        public void onResponse(String json) {

            Log.e("index-------", json);

            mProgressBarRel.setVisibility(View.GONE);

            try {

                homeHeadBean = JSON.parseObject(json, new TypeReference<JsonBaseListBean<HomeHeadBean>>() {
                }.getType());

                views = addHeadView(homeHeadBean.getData());

                setBannerAdapter();
            } catch (JSONException exception) {
                Toast.makeText(mActivity, "网络请求失败", Toast.LENGTH_LONG).show();
            }


        }
    };

    /**
     * 投票  回调
     */
    Response.Listener<String> voteListener = new Response.Listener<String>() {
        @Override
        public void onResponse(String json) {
            Log.d("index vote json", json);

            mProgressBarRel.setVisibility(View.GONE);
            try {

//                voteBean = JSON.parseObject(json, VoteBean.class);
                voteBean = JSON.parseObject(json, new TypeReference<JsonBaseListBean<VoteBean>>() {
                }.getType());

                MetaBean meta = voteBean.getMeta();

                if (meta.getCode() == 200 && meta.getErrorType().equals("SUCCESS")) {
                    setVoteAdapter();
                }
            } catch (JSONException exception) {
                Toast.makeText(mActivity, "网络请求失败", Toast.LENGTH_SHORT).show();
            }
        }
    };

    /**
     * 初始化 adapter
     */
    private void initAdapter() {
        if (newsAdapter == null) {
            newsAdapter = new IndexListViewAdapter(mActivity, newsData.getData());
            listView.setAdapter(newsAdapter);
        } else {
            newsAdapter.fresh(newsData.getData(), isAddAll);
        }
        stop();
    }

    /**
     * 处理首页新闻listview
     */
    private void initListView() {
        Response.Listener<String> listViewListener = new Response.Listener<String>() {
            @Override
            public void onResponse(String json) {
                mProgressBarRel.setVisibility(View.GONE);
                Log.e("index news json", json);
                page = page + 1;
                Log.e("page", page + "page");

                try {
//                    HomeListViewBean homeListViewBean = JSON.parseObject(json, HomeListViewBean.class);
//
//                    newsData = homeListViewBean.getData();

                    newsData = JSON.parseObject(json, new TypeReference<JsonBaseListBean<HomeListViewBean>>() {
                    }.getType());

                    if (newsData != null) {
                        initAdapter();
                    }
                } catch (JSONException exception) {
                    Toast.makeText(mActivity, "网络请求失败", Toast.LENGTH_SHORT).show();
                }
            }
        };

        Response.ErrorListener errorListViewListener = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
                Log.d("index news json", "error  n" +
                        "//'" +
                        "ews json   ...");
            }
        };

        GetVolleyHttp.getInstance(mActivity).getStringGETJsonData(URLConfig.URL_HOME_LIST + "?page=" + page,
                listViewListener, errorListViewListener, (long) 5000);
    }

    /**
     * 刷新加载
     */
    @Override
    public void onRefresh() {
        page = 0;
        isAddAll = false;
        initListView();

    }

    @Override
    public void onLoadMore() {
        isAddAll = true;
        initListView();
    }

    private void stop() {
        listView.stopLoadMore();
        listView.stopRefresh();
        listView.setRefreshTime(DateUtils.getTime());
    }


    /**
     * 版本更新
     */
    private void isNewest() {
        SharePreference sharePreferce = SharePreference.getInstance(getActivity());
        if (!sharePreferce.getBoolean(CacheConfig.CACHE_IS_CLICK_UPDATE_CANCEL)) {


            // 版本判断。当手机系统大于 23 时，才有必要去判断权限是否获取
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

                // 检查该权限是否已经获取
                int i = ContextCompat.checkSelfPermission(mActivity, permissions[0]);
                // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
                if (i != PackageManager.PERMISSION_GRANTED) {
                    // 如果没有授予该权限，就去提示用户请求
//                        PermissionUtil.showDialogTipUserRequestPermission(mActivity, permissions);
                    ActivityCompat.requestPermissions(mActivity, permissions, 321);

                } else {
                    new UpdateManager(getActivity()).checkUpdate();//true
                }

            } else {
                new UpdateManager(getActivity()).checkUpdate();//true
            }
        }
    }

    private List<View> addHeadView(List<HomeHeadBean> dataList) {

        List<View> views = new ArrayList<>();
        for (int i = 0; i < dataList.size(); i++) {
            //TODO:banner文字注释
            View view1 = LayoutInflater.from(mActivity).inflate(R.layout.index_head_viewpager, null);
//            theme = (TextView) view1.findViewById(R.id.index_fragment_theme);
            viewpagerImage = (ImageView) view1.findViewById(R.id.index_fragment_viewpager_img);
//            address = (TextView) view1.findViewById(R.id.index_fragment_address);
//            phoneNumber = (TextView) view1.findViewById(R.id.index_fragment_phoneNumber);
//            joinNumber = (TextView) view1.findViewById(R.id.index_fragment_join_number);

            GetVolleyHttp.getInstance(mActivity).setImageLoader(viewpagerImage,
                    R.drawable.photo_pictures_no, R.drawable.photo_pictures_no, dataList.get(i).getThumbnail());
//            theme.setText(dataList.get(i).getTitle());
//            address.setText(dataList.get(i).getMatchPlace());
//            phoneNumber.setText(dataList.get(i).getPhoneNumber());
//            joinNumber.setText(dataList.get(i).getCount() + "人参加");
            views.add(view1);
        }

        return views;
    }

    private void setCursor(List<View> views) {
        cursorList = new ArrayList<>();
        LinearLayout cursorLayout = (LinearLayout) headView.findViewById(R.id.index_fragment_cursor);

        for (int i = 0; i < views.size(); i++) {
            LinearLayout linearLayout = new LinearLayout(mActivity);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
            params.gravity = Gravity.CENTER_HORIZONTAL;
            params.setMargins(5, 0, 0, 0);

            imageView = new ImageView(mActivity);
            cursorList.add(imageView);

            if (i == 0) {
                cursorList.get(i).setImageResource(R.drawable.index_cursor_selected);
            } else {
                cursorList.get(i).setImageResource(R.drawable.index_cursor);
            }

            linearLayout.addView(cursorList.get(i), params);
            cursorLayout.addView(linearLayout);
        }
    }

    private class MyOnPageChangeListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageScrolled(int i, float v, int i1) {
        }

        @Override
        public void onPageSelected(int position) {

            for (int i = 0; i < cursorList.size(); i++) {
                cursorList.get(i).setImageResource(R.drawable.index_cursor_selected);
                if (position != i) {
                    cursorList.get(i).setImageResource(R.drawable.index_cursor);
                }
            }
        }

        @Override
        public void onPageScrollStateChanged(int i) {

        }
    }

    /**
     * 解决listView addHerderView 的内容为listView 的问题
     *
     * @param listView
     */
    private void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            // pre-condition
            return;
        }

        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }
}

